package com.framework.shiro;


import java.util.List;

import javax.inject.Inject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.config.Ini;
import org.springframework.beans.factory.FactoryBean;

import com.framework.entity.ResFormMap;
import com.framework.mapper.base.BaseMapper;
import com.framework.util.ConfigUtils;


/**
 * 产生责任链，确定每个url的访问权限
 * 
 */
public class ChainDefinitionSectionMetaSource implements FactoryBean<Ini.Section> {

	@Inject
	private BaseMapper baseMapper;
	// 静态资源访问权限
	private String filterChainDefinitions = null;

	
	public Ini.Section getObject() throws Exception {
		/* 
		 * @author bys
		 * 缓存表的字段到内存
		 */
		new ConfigUtils().initTableField();
		/* 
		 * @author bys
		 * shiro section管理
		 *  section 节；部分；段；科

		 */
		Ini ini = new Ini();
		// 加载默认的url
		ini.load(filterChainDefinitions);
		/* 
		 * @author bys
		 * DEFAULT_SECTION_NAME:empty string means the first unnamed section
		 * url 权限容器

		 */
		Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);//
		// 循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,
		// 里面的键就是链接URL,值就是存在什么条件才能访问该链接
		List<ResFormMap> lists = baseMapper.findByNames(new ResFormMap());
		for (ResFormMap resources : lists) {
			// 构成permission字符串
			if (StringUtils.isNotEmpty(resources.get("resUrl") + "") && StringUtils.isNotEmpty(resources.get("resKey") + "")) {
				String permission = "perms[" + resources.get("resKey") + "]";
				System.out.println(permission);
				// 不对角色进行权限验证
				// 如需要则 permission = "roles[" + resources.getResKey() + "]";
				section.put(resources.get("resUrl") + "", permission);
			}

		}
		// 所有资源的访问权限，必须放在最后
		/*section.put("/**", "authc");*/
		section.put("/**", "authc");
		return section;
	}

	/**
	 * 通过filterChainDefinitions对默认的url过滤定义
	 * 
	 * @param filterChainDefinitions
	 *            默认的url过滤定义
	 *            
	 */
	/* 
	 * @author bys
	 * 通过 spring-shiro.xml 管理注入参数 filterChainDefinitions
	 * such as 
	 *      /favicon.ico = anon
    		/admin_files/** = anon
    		/fonts/** = anon
    		/404/** = anon

	 */
	
	public void setFilterChainDefinitions(String filterChainDefinitions) {
		this.filterChainDefinitions = filterChainDefinitions;
	}

	public Class<?> getObjectType() {
		return this.getClass();
	}

	public boolean isSingleton() {
		return false;
	}
}
